<template>
  <div class="product-list-container">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.name" placeholder="商品名称" clearable />
        </el-form-item>

        <el-form-item label="商品分类">
          <el-select v-model="queryParams.categoryId" placeholder="选择分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="品牌">
          <el-select v-model="queryParams.brandId" placeholder="选择品牌" clearable>
            <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮和表格 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" @click="handleAdd">添加商品</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="productList" border style="width: 100%">
        <el-table-column type="index" width="50" label="#" />

        <el-table-column prop="image" label="商品图片" width="100">
          <template #default="scope">
            <el-image style="width: 60px; height: 60px" :src="formatImageUrl(scope.row.image)" fit="cover"
              :preview-src-list="[formatImageUrl(scope.row.image)]" />
          </template>
        </el-table-column>

        <el-table-column prop="name" label="商品名称" show-overflow-tooltip />

        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>

        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>

        <el-table-column prop="brand" label="品牌" width="120">
          <template #default="scope">
            {{ getBrandName(scope.row.brandId) }}
          </template>
        </el-table-column>

        <el-table-column prop="stock" label="库存" width="80" />

        <el-table-column prop="sales" label="销量" width="80" />

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button size="small" @click="handleDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProductList } from '../../api/product'
import { getCategoryList } from '../../api/category'
import { getBrandList } from '../../api/brand'
import { formatImageUrl } from '../../utils/index'

const router = useRouter()
const loading = ref(false)
const productList = ref([])
const categoryOptions = ref([])
const brandOptions = ref([])

// 查询参数
const queryParams = reactive({
  name: '',
  categoryId: undefined,
  brandId: undefined
})

// 获取商品列表
const getList = () => {
  loading.value = true
  getProductList(queryParams)
    .then(res => {
      productList.value = res.data || []
    })
    .catch(error => {
      console.error('获取商品列表失败:', error)
      ElMessage.error('获取商品列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取分类列表
const fetchCategories = () => {
  getCategoryList()
    .then(res => {
      categoryOptions.value = (res.data || []).map(item => ({
        value: item.id,
        label: item.name
      }))
    })
    .catch(error => {
      console.error('获取分类列表失败:', error)
    })
}

// 获取品牌列表
const fetchBrands = () => {
  getBrandList()
    .then(res => {
      brandOptions.value = (res.data || []).map(item => ({
        value: item.id,
        label: item.name
      }))
    })
    .catch(error => {
      console.error('获取品牌列表失败:', error)
    })
}

const getCategoryName = (categoryId) => {
  const category = categoryOptions.value.find(c => c.value === categoryId)
  return category ? category.label : ''
}

const getBrandName = (brandId) => {
  const brand = brandOptions.value.find(b => b.value === brandId)
  return brand ? brand.label : ''
}

// 搜索
const handleQuery = () => {
  getList()
}

// 重置搜索条件
const resetQuery = () => {
  queryParams.name = ''
  queryParams.categoryId = undefined
  queryParams.brandId = undefined
  handleQuery()
}

// 添加商品
const handleAdd = () => {
  router.push('/product/add')
}

// 编辑商品
const handleEdit = (row) => {
  router.push(`/product/edit/${row.id}`)
}

// 查看详情
const handleDetail = (row) => {
  // 可以使用弹窗显示详情，或者跳转到详情页
  ElMessage.info(`查看商品详情: ${row.name}`)
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除商品 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    // 假设存在一个 deleteProduct API
    // deleteProduct(row.id)
    //   .then(() => {
    //     ElMessage.success('删除成功')
    //     getList()
    //   })
    //   .catch(error => {
    //     console.error('删除商品失败:', error)
    //     ElMessage.error('删除商品失败')
    //   })
    //   .finally(() => {
    //     loading.value = false
    //   })
    console.log('删除商品', row.id)
    ElMessage.info('删除功能待实现')
    loading.value = false
  }).catch(() => {
    // 取消删除操作
  })
}

// 初始化
onMounted(() => {
  getList()
  fetchCategories()
  fetchBrands()
})
</script>

<style scoped>
.product-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}
</style>